/**
 * 注册流程状态
 */

 // 默认表单字段
let formDefault = {
  phone_area_code: sessionStorage.getItem('area_code') || '855', //国家区域码
  phone: '',
  potato_area_code: sessionStorage.getItem('area_code') || '354', //国家区域码
  potato: '',
  email: '',
  ver_code: '', //验证码
  password: '',
  by: 1, //登录类型
  init: false, //初始化
}
 export const state = () => {
  return {
    form: {},
    exists: [], //已存在的用户列表
    area_code: sessionStorage.getItem('area_code') || '855', // 默认区号
  }
 }

export const getters = {
  getFormData(state){
    return !!state.form.by ? state.form : JSON.parse(JSON.stringify(formDefault));
  },
  getExists(state){
    return state.exists;
  },
  getAreaCode(state) {
    return state.area_code;
  },
  getPhoneAreaCode(state) {
    return state.form.phone_area_code;
  },
  getPotatoAreaCode(state) {
    return state.form.potato_area_code;
  },
}

 export const mutations = {
  SET_EXISTS (state,list){
    state.exists = list || []
  },
  // 设置表单数据
  // 为防止同时存在email和phone的注册信息
  // GET_AREA_CODE
  SET_FORM (state,form){
    state.form = Object.assign(JSON.parse(JSON.stringify(formDefault)),form || {})
  },

  SET_AREA_CODE (state, area_code, form) {
    // 1 是phone
    if(state.form.init || state.form.init === undefined) {
      state.form = Object.assign(JSON.parse(JSON.stringify(formDefault)),form || {})
      state.form.phone_area_code = area_code;
      state.form.potato_area_code = area_code;
      state.form.init = false;
    }else if(state.form.by == 1) {
      state.form.phone_area_code = area_code
    } else {
      state.form.potato_area_code = area_code
    }
  },
 }

 export const actions = {
  async setAreaCode( {commit, state} ) {
    let area_code = sessionStorage.getItem('area_code');
    if(area_code) {
      commit('SET_AREA_CODE', area_code)
    } else {
      try{
        let {data:rs} = await this.$axios.post('?ct=member&ac=area_code');
        if(rs.code == 0){
          commit('SET_AREA_CODE',rs.data.area_code)
          sessionStorage.setItem('area_code', rs.data.area_code)
        }else{
          this.$toast(rs.msg);
        }
      }catch(e){
        this.$toast('获取区号失败');
        this.$error(e);
      }
    }
  }
 }
